package com.yuliang.ai.logic;

import com.alibaba.fastjson.JSONObject;
import com.yuliang.utils.util.CreateSign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Huangkai
 */
@Slf4j
public class LoginOperationLogic {

    public static String login(String userName, String password) {
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", userName);
            jsonObject.put("password", password);
            jsonObject.put("save_seven_day", 7);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
            HttpPost httpPost = new HttpPost("http://lsjllm.gsdata.cn:8066/api/user/index/login");
            httpPost.setConfig(requestConfig);
            Long time = System.currentTimeMillis() / 1000;
            Map<String, Object> params = new HashMap<>();
            params.put("stime", time);
            params.put("secret", "BearereyJhbGciOiJIUzUxMiJ9");
            String sortStr = CreateSign.getUrlParamsByMap(CreateSign.paramSort(params));
            String sign = DigestUtils.md5Hex(sortStr).toLowerCase();
            httpPost.addHeader("Sign", sign);
            httpPost.addHeader("Stime", String.valueOf(time));

            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setEntity(new StringEntity(jsonObject.toJSONString()));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity content = response.getEntity();
            String responseContent = EntityUtils.toString(content, "UTF-8");
            response.close();
            httpClient.close();
            return responseContent;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}